package com.sk.util.model;

import com.sk.util.SecurityUtil;
import lombok.SneakyThrows;

import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;

/**
 * md5输出流监控
 *
 * @author smy
 * {@code @date} 2022/11/20
 */
public class Md5OutputStream extends OutputStream {
    private final OutputStream os;
    private final MessageDigest md5;
    private long size;

    @SneakyThrows
    public Md5OutputStream(OutputStream outputStream) {
        this.os = outputStream;
        md5 = MessageDigest.getInstance("MD5");
    }

    public String md5() {
        return SecurityUtil.toHex(md5.digest());
    }

    public long size() {
        return size;
    }

    @Override
    public void write(int b) throws IOException {
        os.write(b);
        size += 1;
        md5.update((byte) b);
    }

    @Override
    public void flush() throws IOException {
        os.flush();
    }

    @Override
    public void close() throws IOException {
        os.close();
    }
}
